package casa.depesos.app.com.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.common.base.task.SilentTask;
import com.common.base.task.TaskEngine;
import com.common.base.ui.MyRecyclerView;
import com.date.picker.date.DatePickerDialogFragment;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import casa.depesos.app.com.R;
import casa.depesos.app.com.adapter.PopAdapter;
import casa.depesos.app.com.databinding.ActivityInfoBinding;
import casa.depesos.app.com.frag.EmptyFragment;
import casa.depesos.app.com.frag.NetFailFragment;
import casa.depesos.app.com.http.BaseBean;
import casa.depesos.app.com.http.ReqCallback;
import casa.depesos.app.com.http.bean.MeBean;
import casa.depesos.app.com.http.data.City;
import casa.depesos.app.com.http.data.Me;
import casa.depesos.app.com.http.data.Province;
import casa.depesos.app.com.http.req.MyInfoReq;
import casa.depesos.app.com.http.req.SaveInfoReq;
import casa.depesos.app.com.it.TextChangeListener;
import casa.depesos.app.com.utils.Constant;
import casa.depesos.app.com.utils.Report;
import casa.depesos.app.com.utils.Utils;

public class InfoActivity extends BaseInfoActivity {

    ActivityInfoBinding binding;
    Me info;
    List<Province> list;

    @Override
    public void getData() {
        showLoading();
        clearFragment(getSupportFragmentManager());
        TaskEngine.getInstance().submit(new SilentTask("") {
            @Override
            public void runInBackground() throws Exception {
                getCity();
                int type;
                MeBean bean = new MyInfoReq().req();
                if (bean != null) {
                    if (bean.isValid()) {
                        type = 0;
                        info = bean.info;
                        info.option = 1;
                    } else {
                        type = 1;
                        info = new Me();
                        info.edu = 5;
                        info.marry = 2;
                        info.option = 0;
                        info.child = 1;
                        info.house = 1;
                        info.sex = "M";// M: man, F: woman
                    }
                } else {
                    type = 2;
                }
                h.post(() -> {
                    init(type);
                    check();
                });
            }
        });
    }

    final String title = "Información personal";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityInfoBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        if (Constant.white || fromMe()) {
            if (fromMe()) {
                binding.bottom.setVisibility(View.GONE);
                binding.bg.setBackgroundResource(R.drawable.login_bg);
                int n = binding.linear.getChildCount();
                for (int i = 0; i < n; i++) {
                    View v = binding.linear.getChildAt(i);
                    v.setBackgroundResource(com.date.picker.R.drawable.white_round_bg2);
                }
                List<TextView> tmp = new ArrayList<>();
                tmp.add(binding.sex);
                tmp.add(binding.childNum);
                tmp.add(binding.birth);
                tmp.add(binding.edu);
                tmp.add(binding.merry);
                tmp.add(binding.house);
                tmp.add(binding.area);
                tmp.add(binding.addr);
                tmp.add(binding.app);
                tmp.add(binding.email);
                for (TextView v : tmp) {
                    v.setBackground(null);
                    v.setPadding(0, 0, 0, 0);
                    v.setTextSize(15);
                    v.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
                }
                binding.getRoot().setBackgroundResource(R.color.bg2);
            } else {
                int n = binding.linear.getChildCount();
                int p = Utils.dp2Px(this, 15);
                for (int i = 0; i < n; i++) {
                    View v = binding.linear.getChildAt(i);
                    v.setPadding(p, p, p, 0);
                    ((ViewGroup.MarginLayoutParams) v.getLayoutParams()).topMargin = 0;
                }
                binding.getRoot().setBackgroundResource(R.color.bg2);
            }
            binding.top1.getRoot().setVisibility(View.GONE);
            binding.top2.getRoot().setVisibility(View.VISIBLE);
            binding.top2.top.setPadding(0, Utils.getStatusBarHeight(this), 0, 0);
            binding.top2.back.setEnabled(true);
            binding.top2.back.setOnClickListener(view -> finish());
            binding.top2.title.setText(title);
        } else {
            int n = binding.linear.getChildCount();
            int p = Utils.dp2Px(this, 15);
            for (int i = 0; i < n; i++) {
                View v = binding.linear.getChildAt(i);
                v.setPadding(p, p, p, 0);
                ((ViewGroup.MarginLayoutParams) v.getLayoutParams()).topMargin = 0;
            }
            initTop(binding.top1);
            binding.top2.getRoot().setVisibility(View.GONE);
        }
        Report.show("ACTION_II_001");
        getData();
    }

    private void getCity() {
        try {
            InputStream inputStream = getAssets().open("addr");
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            String fileContent = stringBuilder.toString();
            // 关闭InputStream
            inputStream.close();
            // 将json字符串转换成List
            Type listType = new TypeToken<List<Province>>() {
            }.getType();
            list = new Gson().fromJson(fileContent, listType);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void init(int type) {
        hideLoading();
        fail = false;
        if (type == 2) {
            fail = true;
            replaceFragment(R.id.frame, new NetFailFragment().setTitle(title));
            return;
        } else if (type == 1 && fromMe()) {
            replaceFragment(R.id.frame, new EmptyFragment().setTitle(title));
            return;
        }
        if (info.edu > 1) {
            binding.edu.setText(getValue(R.array.edu, info.edu - 2));
        } else {
            binding.edu.setText(getValue(R.array.edu, info.edu - 1));
        }
        binding.merry.setText(getValue(R.array.merry, info.marry - 1));
        binding.childNum.setText(getValue(R.array.childNum, info.child - 1));
        binding.house.setText(getValue(R.array.house, info.house - 1));
        if ("F".equalsIgnoreCase(info.sex)) {
            binding.sex.setText("M");
        } else {
            binding.sex.setText("H");
            info.sex = "M";
        }
        if (!TextUtils.isEmpty(info.addr)) {
            binding.addr.setText(info.addr);
        }
        if (!TextUtils.isEmpty(info.email)) {
            binding.email.setText(info.email);
        }
        if (!TextUtils.isEmpty(info.app)) {
            binding.app.setText(info.app);
        }
        if (!TextUtils.isEmpty(info.birth)) {
            binding.birth.setText(info.birth);
        }

        if (!TextUtils.isEmpty(info.liveDes)) {
            if (fromMe() || Constant.white) {
                binding.area.setText(info.liveDes);
            }
            for (Province p : list) {
                for (City c : p.list) {
                    String tmp = c.province + c.name;
                    String tmp2 = c.province + "," + c.name;
                    if (tmp.equalsIgnoreCase(info.liveDes) || tmp2.equalsIgnoreCase(info.liveDes)) {
                        info.live = c.provinceCode + "," + c.code;
                        binding.area.setText(tmp2);
                        break;
                    }
                }
            }
        }
        binding.sex.setListener(new TextChangeListener() {
            @Override
            public void onTextChange(String txt, int index) {
                if ("H".equals(txt)) {
                    info.sex = "M";
                } else {
                    info.sex = "F";
                }
            }
        });
        chooseValue(binding.sex, R.array.sex, info, "sex", "Género");
        chooseValue(binding.childNum, R.array.childNum, info, "child", "Número de hijos");
        chooseValue(binding.edu, R.array.edu, info, "edu", "Nivel educativo");
        chooseValue(binding.merry, R.array.merry, info, "marry", "Estado civil");
        chooseValue(binding.house, R.array.house, info, "house", "Tipo de vivienda");
        choose2Value(binding.area, list, info, "Zona de residencia");

        binding.email.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                check();
                if (editable.toString().endsWith("@")) {
                    showPop(binding.email, editable.toString().trim());
                } else {
                    hidePop();
                }
            }
        });
        binding.addr.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                check();
            }
        });
        Utils.setEditTextInputNoSpaceStart(binding.addr, 100);
        Utils.setEditTextEmail(binding.email, 50);
        Utils.setNumberEditTextInputSpace(binding.app, 10);

        binding.birth.setOnClickListener(view -> {
            //todo
            DatePickerDialogFragment dlg = new DatePickerDialogFragment();
            dlg.setOnDateChooseListener(new DatePickerDialogFragment.OnDateChooseListener() {
                @Override
                public void onDateChoose(int i, int i1, int i2) {
                    StringBuffer sb = new StringBuffer();
                    if (i2 < 10) {
                        sb.append(0);
                    }
                    sb.append(i2).append("-");
                    if (i1 < 10) {
                        sb.append(0);
                    }
                    sb.append(i1).append("-").append(i);

                    binding.birth.setText(sb.toString());
                    check();
                }
            });
            dlg.show(getSupportFragmentManager(), "");
        });
        binding.next.setOnClickListener(view -> {
            if (!checkValue()) {
                return;
            }
            showLoading();
            Report.click("ACTION_II_003");
            new SaveInfoReq(info).req(new ReqCallback() {
                @Override
                public void callback(boolean success, BaseBean bean) {
                    hideLoading();
                    if (success || Constant.white) {
                        if (getIntent().getIntExtra("from", 0) == 1) {
                            finish();
                        } else {
                            if (Constant.white) {
                                Utils.setStatus(20);
                            }
                            Intent i = new Intent(InfoActivity.this, WorkActivity.class);
                            i.putExtras(getIntent());
                            startActivity(i);
                            finish();
                        }
                    }
                }
            });
        });
    }

    private boolean checkValue() {
        boolean result = true;
        String birth = binding.birth.getText().toString().trim();
        if (TextUtils.isEmpty(birth)) {
            result = false;
            binding.birthErr.setVisibility(View.VISIBLE);
        } else {
            info.birth = birth;
            binding.birthErr.setVisibility(View.GONE);
        }
        String area = binding.area.getText().toString().trim();
        if (TextUtils.isEmpty(area)) {
            result = false;
            binding.areaErr.setVisibility(View.VISIBLE);
        } else {
            binding.areaErr.setVisibility(View.GONE);
        }
        String addr = binding.addr.getText().toString().trim();
        if (TextUtils.isEmpty(addr)) {
            result = false;
            binding.addrErr.setVisibility(View.VISIBLE);
        } else {
            info.addr = addr;
            binding.addrErr.setVisibility(View.GONE);
        }
        String email = binding.email.getText().toString().trim();
        if (TextUtils.isEmpty(email) || !Utils.isEmail(email)) {
            result = false;
            binding.emailErr.setVisibility(View.VISIBLE);
        } else {
            info.email = email;
            binding.emailErr.setVisibility(View.GONE);
        }
        String app = binding.app.getText().toString().trim();
        if (!TextUtils.isEmpty(app)) {
            if (app.length() == 10) {
                info.app = app;
            } else {
                result = false;
                binding.appErr.setVisibility(View.VISIBLE);
            }
        }
        return result;
    }

    final PopRunnable popRunnable = new PopRunnable();

    @Override
    protected int getIndex() {
        return 0;
    }

    class PopRunnable implements Runnable {

        View view;
        String str;

        public PopRunnable setParam(View v, String s) {
            this.view = v;
            this.str = s;
            return this;
        }

        @Override
        public void run() {
            showPopWin(view, str);
        }
    }

    private void showPop(View view, String str) {
        h.removeCallbacks(popRunnable);
        h.postDelayed(popRunnable.setParam(view, str), 600);
    }

    private void hidePop() {
        h.removeCallbacks(popRunnable);
        if (mPopupWindow == null) {
            return;
        }
        mPopupWindow.dismiss();
    }

    PopupWindow mPopupWindow = null;
    PopAdapter popAdapter;

    private void showPopWin(View anchor, String str) {
        if (mPopupWindow == null) {
            View view = LayoutInflater.from(this).inflate(R.layout.pop_list, null);
            MyRecyclerView recyclerView = view.findViewById(R.id.list);
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            popAdapter = new PopAdapter(this, recyclerView, str);
            recyclerView.setAdapter(popAdapter);

            mPopupWindow = new PopupWindow();
//设置PopupWindow是否能响应外部点击事件
            mPopupWindow.setOutsideTouchable(true);
            mPopupWindow.setTouchable(true);
            mPopupWindow.setContentView(view);
            mPopupWindow.setWidth(anchor.getWidth());
            mPopupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        } else {
            popAdapter.update(str);
        }
//确定弹窗的基于哪个父视图，大小，位置。
        if (!mPopupWindow.isShowing()) {
            mPopupWindow.showAsDropDown(anchor, 0, Utils.dp2Px(this, 5));
        }
    }

    public void setEmail(String str) {
        binding.email.setText(str);
        Utils.hideInput(binding.email);
    }

    @Override
    protected void check() {
        //show error after submit
        binding.birthErr.setVisibility(View.GONE);
        binding.areaErr.setVisibility(View.GONE);
        binding.addrErr.setVisibility(View.GONE);
        binding.emailErr.setVisibility(View.GONE);
        binding.appErr.setVisibility(View.GONE);

        String birth = binding.birth.getText().toString();
        String area = binding.area.getText().toString();
        String addr = binding.addr.getText().toString().trim();
        String email = binding.email.getText().toString().trim();
        boolean bo = isValid(birth, area, addr, email);
        if (bo) {
            binding.next.setAlpha(1f);
        } else {
            binding.next.setAlpha(0.6f);
        }
    }

    private boolean isValid(String... str) {
        for (String s : str) {
            if (TextUtils.isEmpty(s)) {
                return false;
            }
        }
        return true;
    }
}
